package com.fingard.dsp.bank.directbank.cmb01;


import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

@Component("CMB01Balance")
public class CMB01Balance extends CMB01Base implements IBalance {
    /**
     * 即时余额查询
     * @param p_req7506
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        String isSetSleep = getBankConfig().getValueAsString("useSleepGetQuery");
        if ("true".equals(isSetSleep.toLowerCase())) {
            long realSleepTime = getBankConfig().getValueAsInt("QuerySleepTime");
            if (realSleepTime < 0) {
                realSleepTime = 0;
            }
            Thread.sleep(realSleepTime * 1000);
        }

        p_req7506.readRecord();
        if((StringHelper.hasAnyChar(p_req7506.readedDetail.higherLevelAct) && StringHelper.hasAnyChar(p_req7506.readedDetail.actNum)) || p_req7506.readedDetail.isVirtual){
            return d_7506_BalQry_Virtual(p_req7506);
        }else {
            if (getBankConfig().getValueAsBool("useOldQryBal")) {
                return d_7506_BalQry_Old(p_req7506);
            } else {
                return d_7506_BalQry_New(p_req7506);
            }
        }
    }


    public RetAts7506BalQry d_7506_BalQry_Old(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "GetAccInfo";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            p_req7506.resetReadMode();
            while (p_req7506.readRecord()) {
                xmlWriter.writeStartElement("SDKACINFX");
                xmlWriter.writeElementString("BBKNBR", p_req7506.readedDetail.actArea);
                xmlWriter.writeElementClosed("C_BBKNBR");
                xmlWriter.writeElementString("ACCNBR", p_req7506.readedDetail.actNum);
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7506.reqHeader.transType, p_req7506.reqHeader.transType);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        while (tmpBkReader.read("/CMBSDKPGK/NTQACINFZ")) {
                            RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();

                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.actArea = tmpBkReader.readedXElement.getSingleText("BBKNBR");
                            tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("ONLBLV");
                            tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("AVLBLV");

                            tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CCYNBR"));
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("ACCNBR");

                            retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpBkReader.getSimpleText("ERRMSG"));
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpRetBkStr[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAts7506BalQry d_7506_BalQry_Virtual(Req7506BalQry p_req7506) throws Exception {
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTDMABAL";//"GetAccInfo";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            p_req7506.resetReadMode();
            while (p_req7506.readRecord()) {
                xmlWriter.writeStartElement("NTDMABALX");
                String higherLevelAct = p_req7506.readedDetail.higherLevelAct;
                if(StringHelper.hasAnyChar(higherLevelAct)){
                    xmlWriter.writeElementString("ACCNBR", p_req7506.readedDetail.higherLevelAct);//主体账户
                }else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("请求报文中ACCNBR节点为空，请检查CMB01/config.xml中'higherLevelAct'节点配置");
                    retAts.writeEnd();
                    return retAts;
                }
                //截取虚拟户编号 实体+编号
                String virtualNo = p_req7506.readedDetail.actNum.replace(higherLevelAct,"");
                xmlWriter.writeElementString("DMANBR", virtualNo);//虚拟户编号
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if(tmpRetCode.equals("0")){
                    while (tmpBkReader.read("/CMBSDKPGK/NTDMABALZ")) {
                            RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();

                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("DMACCY"));
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("DMANBR");
                            tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleTextNotNull("ACTBAL");
                            tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleTextNotNull("ACTBAL");
                            //虚拟账户无冻结余额
                       //     tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleTextNotNull("HLDBLV");
                            //ACCBLV	上日余额
                       //     tmpRetDetail.yesterdayBal = tmpBkReader.readedXElement.getSingleTextNotNull("ACCBLV");

                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    }
                    }else{
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpRetBkStr[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAts7506BalQry d_7506_BalQry_New(Req7506BalQry p_req7506) throws Exception {
        //余额查询
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTQADINF";//"GetAccInfo";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            p_req7506.resetReadMode();
            while (p_req7506.readRecord()) {
                xmlWriter.writeStartElement("NTQADINFX");
                xmlWriter.writeElementString("BBKNBR", p_req7506.readedDetail.actArea);
                xmlWriter.writeElementString("ACCNBR", p_req7506.readedDetail.actNum);
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
//            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7506.reqHeader.transType, p_req7506.reqHeader.transType);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    while (tmpBkReader.read("/CMBSDKPGK/NTQADINFZ")) {
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                        String tmpERRCOD = tmpBkReader.readedXElement.getSingleTextNotNull("ERRCOD");
                        if (tmpERRCOD.equals("SUC0000")) {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.actArea = tmpBkReader.readedXElement.getSingleTextNotNull("BBKNBR");
                            tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("CCYNBR"));
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("ACCNBR");
                            tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleTextNotNull("ONLBLV");
                            tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleTextNotNull("AVLBLV");
                            //HLDBLV	冻结余额	M		可
                            tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleTextNotNull("HLDBLV");
                            //ACCBLV	上日余额
                            tmpRetDetail.yesterdayBal = tmpBkReader.readedXElement.getSingleTextNotNull("ACCBLV");
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("ACCNBR");

                            String tmpERRTXT = tmpBkReader.readedXElement.getSingleTextNotNull("ERRTXT");

                            tmpRetDetail.respInfo = StringHelper.joinNotEmpty("-", tmpERRCOD, tmpERRTXT);
                        }
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpRetBkStr[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 历史余额查询
     * @param p_req7505
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        String isSetSleep = getBankConfig().getValueAsString("useSleepGetQuery");
        if ("true".equals(isSetSleep.toLowerCase())) {
            long realSleepTime = getBankConfig().getValueAsInt("QuerySleepTime");
            if (realSleepTime < 0) {
                realSleepTime = 0;
            }
            Thread.sleep(realSleepTime * 1000);
        }
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "SDKNTQABINF";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, tmpBnkHeader);

            xmlWriter.writeStartElement("NTQABINFY");
            xmlWriter.writeElementString("BBKNBR", p_req7505.actArea);
            xmlWriter.writeElementString("ACCNBR", p_req7505.actNum);
            xmlWriter.writeElementString("BGNDAT", p_req7505.dateFrom);
            xmlWriter.writeElementString("ENDDAT", p_req7505.dateTo);
            xmlWriter.writeEndElement();

            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRETCOD = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpERRMSG = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRETCOD != null && tmpRETCOD.equals("0")) {
                        while (tmpBkReader.read("/CMBSDKPGK/NTQABINFZ")) {
                            RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                            String tmpETYDAT = tmpBkReader.readedXElement.getSingleText("ETYDAT");
                            if (tmpETYDAT.length() == 8) {
                                tmpRetDetail.balDate = tmpETYDAT.substring(0, 4) + "-" + tmpETYDAT.substring(4, 6) + "-" + tmpETYDAT.substring(6, 8);
                            } else {
                                tmpRetDetail.balDate = tmpETYDAT;
                            }
                            tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleText("BALAMT");
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpERRMSG;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpRetBkStr[1];
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }
}
